github.com/mikejeuga/temperature-converter@v0.0.0-20220721135550-2cf6fcec7145/back-box-tests/acceptancehelpers/web/api_ client.go (about) 1 package web 2 3 import ( 4 "fmt" 5 "github.com/mikejeuga/temperature-converter/models" 6 "io" 7 "net/http" 8 "path/filepath" 9 "strconv" 10 "time" 11 ) 12 13 type APIClient struct { 14 baseURL string 15 httpDriver *http.Client 16 } 17 18 func NewAPIClient() *APIClient { 19 baseURL := "http://localhost:8069" 20 client := &http.Client{ 21 Transport: http.DefaultTransport, 22 Timeout: 5 * time.Second, 23 } 24 return &APIClient{baseURL: baseURL, httpDriver: client} 25 } 26 27 func (c *APIClient) ConvertCtoF(temp models.Celsius) (models.Fahrenheit, error) { 28 url := c.baseURL + "/to-fahrenheit/" + fmt.Sprintf("%v", temp) 29 30 resp, err := c.httpDriver.Get(url) 31 if err != nil { 32 return 0, fmt.Errorf("problem reaching out %s, %w", url, err) 33 } 34 defer resp.Body.Close() 35 36 if resp.StatusCode != http.StatusOK { 37 return 0, fmt.Errorf("unexpected response code %d but expected %d from %s", resp.StatusCode, http.StatusOK, url) 38 } 39 40 fahrenheit, err := io.ReadAll(resp.Body) 41 if err != nil { 42 return 0, err 43 } 44 45 temperatureResponse, err := strconv.ParseFloat(string(fahrenheit), 64) 46 if err != nil { 47 return 0, err 48 } 49 50 return models.Fahrenheit(temperatureResponse), nil 51 } 52 53 func (c *APIClient) ConvertFtoC(temp models.Fahrenheit) (models.Celsius, error) { 54 url := c.baseURL + "/to-celsius/" + fmt.Sprintf("%v", temp) 55 56 resp, err := c.httpDriver.Get(url) 57 if err != nil { 58 return 0, fmt.Errorf("problem reaching out %s, %w", url, err) 59 } 60 defer resp.Body.Close() 61 62 if resp.StatusCode != http.StatusOK { 63 return 0, fmt.Errorf("unexpected response code %d but expected %d from %s", resp.StatusCode, http.StatusOK, url) 64 } 65 66 fahrenheit, err := io.ReadAll(resp.Body) 67 if err != nil { 68 return 0, err 69 } 70 71 temperatureResponse, err := strconv.ParseFloat(string(fahrenheit), 64) 72 if err != nil { 73 return 0, err 74 } 75 76 filepath.Join() 77 78 return models.Celsius(temperatureResponse), nil 79 }